<?php

namespace App\Http\Controllers\Archive;

use App\Http\Controllers\Controller;
use App\Repositories\Contracts\CategoryRepositoryInterface;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class CategoryController extends Controller {

  /**
   * @var \App\Repositories\CategoryRepository
   */
  private $categoryRepository;

  public function __construct( CategoryRepositoryInterface $categoryRepository ) {
    $this->categoryRepository = $categoryRepository;
  }

  public function lists( $id = null, Request $request ) {
    $result = $this->categoryRepository->paginate();

    return response()->json( [ 'success' => true, 'data' => $result ] );
  }

  public function save( Request $request ) {
    \Log::debug("eee");
    $id   = intval( $request->input( "id", 0 ) );
    $data = $request->only( 'name', 'alias', 'template_name' );
    $this->categoryValidation( $data )->validate();
    if ( $id > 0 ) {
      $data = $this->categoryRepository->updateRich( $data, $id );
    } else {
      $data = $this->categoryRepository->create( $data );
    }

    return $this->result( $data != null, $data );
  }

  public function categoryValidation( array $data ) {

    $roles = [
      'name'          => [ 'required', 'string', 'max:255' ],
      'alias'         => [ 'required', 'string', 'max:255' ],
      'template_name' => 'required|string|min:6'
    ];

//    if ( $id < 1 ) {
//      // 新用户做唯一性检测
//      $roles['name'][]  = "unique:users,name";
//      $roles['email'][] = "unique:users,email";
//    } else {
//      // 老用户不能与其它人同名
//      $roles['name'][]  = Rule::unique( 'users' )->ignore( $id );
//      $roles['email'][] = Rule::unique( 'users' )->ignore( $id );
//      // 没有设置密码时忽略
//      if ( ! $data['password'] ) {
//        unset( $roles['password'] );
//      }
//    }

    return Validator::make( $data, $roles );

  }


  public function remove( $id = null, Request $request ) {
    $id = intval( $id );
    if ( $id < 0 ) {
      return $this->result( false );
    }
    $result = $this->categoryRepository->delete( $id );

    return $this->result( $result > 0 );
  }
}
